﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DingApi.Models;
using System.Data;

using System.Web;
using System.IO;
using System.Text;
using Dingding.Helper;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NCommon;


namespace DingApi.Controllers
{
    [RoutePrefix("api/UpDownFileFtp")]
    public class UpDownFileFtpController : ApiController
    {
         
        private string s_ftp_ip     = "10.10.12.104/";//ftp 地址；
        
        //120 服务器；
        //private string s_ftp_http   = "http://58.210.172.37:8050/pics/";//http图片浏览地址
        //104服务器；
        private string s_ftp_http   = "http://58.210.172.37:8019/";//http图片浏览地址

       
        //目录名；最多支持3层目录名；分别为md1,md2,md3,s_ftp_mdd最终目录名
        private string s_ftp_md1   = string.Empty;       
        private string s_ftp_md2   = string.Empty;
        private string s_ftp_md3   = string.Empty;
        private string s_ftp_mdd   = string.Empty;

        private string userName = "lt";
        private string password = "8ik,.lo9";

      

        /// <summary>
        /// //目 
        /// </summary>
        /// <param name="BILL_TYPE"></param>
        /// <param name="BILL_NO"></param>
        /// <param name="NAME_TYPE"> //目录名ML；web浏览地址 WEB </param>
        /// <returns></returns>
        public void getDirOrName(string BILL_TYPE, string BILL_NO)
        {
            //资材采购收货；
            if (BILL_TYPE == "PASI")
            {

                this.s_ftp_ip = s_ftp_ip + "_pic_new/pasi/";
                this.s_ftp_md1 = BILL_NO.Substring(2, 3);
                this.s_ftp_md2 = BILL_NO;
                this.s_ftp_http = s_ftp_http + "_pic_new/pasi/" + s_ftp_md1 + "/" + s_ftp_md2 + "/";
            }

            //资材图片
            else if (BILL_TYPE == "PAEF")
            {
                this.s_ftp_ip = s_ftp_ip + "_PA/";
                this.s_ftp_md1 = BILL_NO;
                this.s_ftp_http = s_ftp_http + "_PA/" + s_ftp_md1 + "/";
            }

            //质量在线封锁图片
            else if (BILL_TYPE == "DCXA")
            {
                this.s_ftp_ip = s_ftp_ip + "DCXA/";
                this.s_ftp_md1 = BILL_NO.Substring(0, 6);
                this.s_ftp_md2 = BILL_NO;
                this.s_ftp_http = s_ftp_http + "DCXA/" + s_ftp_md1 + "/" + s_ftp_md2 + "/";               
            }

            this.s_ftp_mdd = this.s_ftp_md1 + "/";

            if (s_ftp_md2 != "")
            {
                this.s_ftp_mdd = this.s_ftp_mdd + "/" + this.s_ftp_md2 + "/";
            }
            if (s_ftp_md3 != "")
            {
                this.s_ftp_mdd = this.s_ftp_mdd + "/" + this.s_ftp_md3 + "/";
            }
        }



        



        [HttpPost]
        [Route("PostUpFile")]

        //FTP上传图片OK
        public HttpResponseMessage PostUpFile()
        {
            string msg = "";

            //类型；
            string BILL_TYPE = HttpContext.Current.Request.Form["BILL_TYPE"];
            //关键字，如单号或材料号
            string BILL_NO = HttpContext.Current.Request.Form["BILL_NO"];
            //文件命名关键字；（文件名头开始的字符）
            string NAME_SUB = HttpContext.Current.Request.Form["NAME_SUB"];

            this.getDirOrName(BILL_TYPE, BILL_NO);
          

           
          
            //打开ftp
            MyFft ftp = new MyFft(this.s_ftp_ip, this.userName, this.password);

            //创建目录；
            if (this.s_ftp_md1!="")
            {
                ftp.MakeDirectory(this.s_ftp_md1);
            }
            if (this.s_ftp_md2 != "")
            {
                ftp.MakeDirectory(this.s_ftp_md1 + "/" + this.s_ftp_md2);
            }
            if (this.s_ftp_md3 != "")
            {
                ftp.MakeDirectory(this.s_ftp_md1 + "/" + this.s_ftp_md2 + "/" + this.s_ftp_md3);
            }


            //切换止当前目录
            ftp.GotoDirectory(this.s_ftp_mdd);

            //虽然支持多记录
            int count = HttpContext.Current.Request.Files.Count;

            for (int i = 0; i < count; i++)
            {
                try
                {
                    HttpPostedFile file = HttpContext.Current.Request.Files[i];
                    var fileExt = Path.GetExtension(file.FileName);
                    var fileName = NAME_SUB + "_" 
                        + DateTime.Now.ToString("ddHHmmssfff") + "_" 
                        + Guid.NewGuid().ToString("n").Substring(0, 5)
                        + fileExt;
                     

                    //可以的；效率不及如下；
                    //var mapPath = "";
                    //mapPath = "D:\\pic\\_DCXA2\\"; 
                  
                    //var mapPathFullPath = mapPath + fileName + fileExt; //硬盘物理路径
                    //if (!Directory.Exists(mapPath))
                    //{
                    //    Directory.CreateDirectory(mapPath);
                    //}
                    //file.SaveAs(mapPathFullPath); 
                                
                    //ftp.UploadFile(mapPathFullPath,false);






                    //效率高，直接读取文件流；                   
                    byte[] photoValue = new byte[file.ContentLength];
                    file.InputStream.BeginRead(photoValue, 0, file.ContentLength, null, "1");
                  
                    ftp.UploadFile(photoValue, fileName, true);

                  

                }
                catch (Exception ex)
                {
                    msg = ex.ToString();
                }
            }
            
            HttpResponseMessage result = new HttpResponseMessage
            {
                Content = new StringContent(msg, Encoding.GetEncoding("UTF-8"), "application/json")
            };
            return result;
        }



        //删除
        [HttpPost]
        [Route("PostDelFiles")]
        public System.Data.DataSet PostDelFiles([FromBody]  JObject obj)
        {

            string BILL_TYPE    = obj["BILL_TYPE"] == null ? " " : obj["BILL_TYPE"].ToString();
            string BILL_NO      = obj["BILL_NO"] == null ? " " : obj["BILL_NO"].ToString();
            string NAME_SUB     = obj["NAME_SUB"] == null ? " " : obj["NAME_SUB"].ToString();


            this.getDirOrName(BILL_TYPE, BILL_NO);

            //打开ftp
            MyFft ftp = new MyFft(this.s_ftp_ip + this.s_ftp_mdd, this.userName, this.password);

            string[] str = ftp.LisFiles("");


            EI.EIInfo outBlock = new EI.EIInfo();  
            for (int i = 0; i < str.Length; i++)
            {
                ftp.DeleteFile(str[i]);
            }
           
          

            //系统信息；
            outBlock.Tables.Add("SYS");
            outBlock.Tables["SYS"].Columns.Add("FLAG");
            outBlock.Tables["SYS"].Columns.Add("MSG");
            outBlock.Tables["SYS"].Rows.Add(outBlock.sys_info.flag, outBlock.sys_info.msg);
            return outBlock;

        }


        //浏览图片OK
        [HttpPost]
        [Route("PostViewFiles")]
        public System.Data.DataSet PostViewFiles([FromBody]  JObject obj)
        {

            string BILL_TYPE = obj["BILL_TYPE"] == null ? " " : obj["BILL_TYPE"].ToString();
            string BILL_NO = obj["BILL_NO"] == null ? " " : obj["BILL_NO"].ToString();
            string NAME_SUB = obj["NAME_SUB"] == null ? " " : obj["NAME_SUB"].ToString();


            this.getDirOrName(BILL_TYPE, BILL_NO);

            //打开ftp
            MyFft ftp = new MyFft(this.s_ftp_ip + this.s_ftp_mdd, this.userName, this.password);

            string[] str = ftp.LisFiles("");


            EI.EIInfo outBlock = new EI.EIInfo();
            outBlock.Tables[0].TableName = "FILES";

            outBlock.Tables["FILES"].Columns.Add("FURL");
            outBlock.Tables["FILES"].Columns.Add("FNAME");
            outBlock.Tables["FILES"].Columns.Add("FTYPE");

            for (int i = 0; i < str.Length; i++)
            {
                if (NAME_SUB.Trim() != "" && NAME_SUB.Trim() != "*")
                {
                    if (str[i].StartsWith(NAME_SUB))
                    {
                        outBlock.Tables["FILES"].Rows.Add(this.s_ftp_http + str[i]
                            , str[i]
                            , Path.GetExtension(str[i])
                            );
                    }
                }
                else
                {
                        outBlock.Tables["FILES"].Rows.Add(this.s_ftp_http + str[i]
                             , str[i]
                             , Path.GetExtension(str[i])
                             );
                }
               
            }



            //系统信息；
            outBlock.Tables.Add("SYS");
            outBlock.Tables["SYS"].Columns.Add("FLAG");
            outBlock.Tables["SYS"].Columns.Add("MSG");
            outBlock.Tables["SYS"].Rows.Add(outBlock.sys_info.flag, outBlock.sys_info.msg);
            return outBlock;

        }  
        






         //获取单据下的图片数量OK
        [HttpPost]
        [Route("PostGetFilesNum")]
        public System.Data.DataSet PostGetFilesNum([FromBody]  JObject obj)
        {

            string BILL_TYPE    = obj["BILL_TYPE"]  == null ? " " : obj["BILL_TYPE"].ToString();
            string BILL_NO      = obj["BILL_NO"]    == null ? " " : obj["BILL_NO"].ToString();
            string NAME_SUB     = obj["NAME_SUB"]   == null ? " " : obj["NAME_SUB"].ToString();

            int files_num = PostGetFilesNum(BILL_TYPE,BILL_NO,NAME_SUB);
           
            EI.EIInfo outBlock = new EI.EIInfo();
            outBlock.Tables[0].TableName = "FILES";
            outBlock.Tables["FILES"].Columns.Add("NUM");
            outBlock.Tables["FILES"].Rows.Add(files_num);
             



            //系统信息；
            outBlock.Tables.Add("SYS");
            outBlock.Tables["SYS"].Columns.Add("FLAG");
            outBlock.Tables["SYS"].Columns.Add("MSG");
            outBlock.Tables["SYS"].Rows.Add(outBlock.sys_info.flag, outBlock.sys_info.msg);
            return outBlock;

        }

        /// <summary>
        /// ok中间函数
        /// </summary>
        /// <param name="BILL_TYPE"></param>
        /// <param name="BILL_NO"></param>
        /// <param name="NAME_SUB"></param>
        /// <returns></returns>
        public int  PostGetFilesNum(string BILL_TYPE, string BILL_NO, string NAME_SUB)
        {

            this.getDirOrName(BILL_TYPE, BILL_NO);         
            //打开ftp
            MyFft ftp = new MyFft(this.s_ftp_ip + "/" + this.s_ftp_mdd + "/", this.userName, this.password);

            string[] str = ftp.LisFiles("");

            int k = 0;
            
            if (str != null)
            {
                
                if (NAME_SUB.Trim() == "*" || NAME_SUB.Trim() == "")
                {
                    k = str.Length;
                }  
                else
                {
                    for (int i = 0; i < str.Length; i++)
                    {
                        if (str[i].ToString().StartsWith(NAME_SUB))
                            k++;
                    }
                }
            }
            return k;
            
        }

          

  

         

         
    }
}